<template>
  <div class="device-list">
    <div class="device-list-header">
      <div class="device-list-header-form">
        <DynamicForm
            ref="dynamicFormRef"
            type="search"
            @click="callBack"
            :rulesForm="state.deviceForm"
            :refresh="state.refresh"
        />
      </div>
      <div class="device-list-header-button">
        <el-button type="primary" @click="addDevice">新增</el-button>
      </div>
    </div>
    <div class="device-list-table">
      <DynamicTable
          ref="dynamicTableRef"
          :columns="device"
          :table="state.table"
          :data="state.data"
          @click="callBack"
      />
    </div>
    <DynamicDialog ref="dynamicDialogRef" @click="callBack" :dialogVisible="state.visible" :button="state.button"
                   title="添加记录">
      <template #dialog>
        <DynamicForm ref="dynamicFormRef" @click="callBackDialog" :rulesForm="state.deviceRecordForm"
                     :rules="state.deviceRecordRules"
                     :refresh="state.dialogRefresh"
                     width="500px"/>
      </template>
    </DynamicDialog>
    <DynamicDialog ref="dynamicReplaceDialog" @click="callBackReplace" :dialogVisible="state.replaceVisible"
                   :button="state.button"
                   title="设备流转">
      <template #dialog>
        <DynamicForm ref="dynamicReplaceFormRef" @click="callBackReplace" :rulesForm="state.replaceForm"
                     :refresh="state.replaceRefresh"
                     :rules="state.replaceRules"
                     width="500px"/>
      </template>
    </DynamicDialog>
    <DynamicDialog ref="dynamicDialogRef" @click="callBack" :dialogVisible="state.historyVisible" :button="state.button"
                   title="设备历史数据">
      <template #dialog>
        <History v-if="state.historyVisible" ref="historyRef" :row="state.row"/>
      </template>
    </DynamicDialog>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, reactive} from 'vue';
import {useRouter} from 'vue-router';

import DynamicTable from '@/components/layout/table/dynamic-table.vue';
import DynamicForm from '@/components/layout/form/dynamic-form.vue';
import DynamicDialog from '@/components/layout/dialog/dynamic-dialog.vue';
import History from '../history/Index.vue';

import {deviceColumns} from '@/assets/script/middle/columns/device';
import {
  deviceForm,
  deviceRepairRecordForm,
  deviceScrapRecordForm,
  deviceRecordRules, deviceReplaceForm, deviceReplaceRules
} from '@/assets/script/middle/forms/device/device-form';

import {listConstByDictionaryCodesApi} from '@/api/dictionary';
import {listOrganizationApi} from '@/api/organization';
import {listDevicePageApi} from '@/api/device';
import {addBmsDeviceRepairApi} from "@/api/device/repair";
import {ElMessage} from "element-plus";
import {addBmsDeviceReplaceApi} from "@/api/device/replace";

const historyRef = ref(History);
const dynamicTableRef = ref(DynamicTable);
const dynamicFormRef = ref(DynamicForm);
const dynamicDialog = ref(DynamicDialog);
const dynamicReplaceFormRef = ref(DynamicForm);
const dynamicReplaceDialog = ref(DynamicDialog);

const router = useRouter()
const device = deviceColumns;

const state = reactive({
  data: [],
  table: {
    total: 0,
    pageSize: 15,
    pageIndex: 1,
  },
  organizationList: [],
  deviceForm: JSON.parse(JSON.stringify(deviceForm)),
  deviceRecordForm: JSON.parse(JSON.stringify(deviceRepairRecordForm)),
  deviceRecordRules: deviceRecordRules,
  storey: [],
  floor: [],
  room: [],
  refresh: 0,
  dialogRefresh: 0,
  searchData: {} as any,
  row: {} as any,
  visible: false,
  historyVisible: false,
  button: {
    cancel: false,
    confirm: false,
  },
  replaceForm: [],
  replaceRules: deviceReplaceRules,
  replaceRefresh: 0,
  replaceVisible: false
});

onMounted(() => {
  const card = state.deviceRecordForm[0].card
  let repairType = card.find(({name = ''}) => name == 'repairType')
  if (repairType) {
    repairType['repairType'] = 0;
  }
  listDictionary(['device']);
  listOrganization({deleted: 0});
  listDevicePage()
})

const callBackReplace = (data: any) => {
  switch (data.type || '') {
    case 'dialogClose':
      state.replaceVisible = false
      break
    case 'submit':
      if (data.data) {
        let params = data.data;
        if (params['targetOrganizationIdName']) {
          params['targetOrganizationName'] = params['targetOrganizationIdName']
        }
        const targetOrganization = state.organizationList.find((f: any) => f.id === params['targetOrganizationId']) || {
          name: '',
          parentId: ''
        }
        params['topOrganizationId'] = (targetOrganization?.parentId && targetOrganization?.parentId != '0') ?
            targetOrganization?.parentId : params['targetOrganizationId']
        // 当前机构
        const sourceOrganization = state.organizationList.find((f: any) => f.id === state.row.organizationId) || {id: ''}
        if (sourceOrganization) {
          params['sourceOrganizationId'] = sourceOrganization.id
        }
        params["deviceId"] = state.row.id
        addBmsDeviceReplaceApi(params).then((data: any) => {
          if (data.code === 0) {
            ElMessage.success({message: '保存成功！'})
            state.replaceVisible = false
            let searchParams = state.searchData
            listDevicePage(searchParams)
          } else {
            console.log('callBackDialog', data)
            ElMessage.warning({message: '保存失败！'})
          }
        })

      }
      break
  }
}

const callBackDialog = (data: any) => {
  switch (data.type || '') {
    case 'repairType':
      if (data.data == 0) {
        state.deviceRecordForm = JSON.parse(JSON.stringify(deviceRepairRecordForm))
      } else {
        state.deviceRecordForm = JSON.parse(JSON.stringify(deviceScrapRecordForm))
      }
      // eslint-disable-next-line no-case-declarations
      const card = state.deviceRecordForm[0].card
      // eslint-disable-next-line no-case-declarations
      let repairType = card.find(({name = ''}) => name == 'repairType')
      if (data.data == 0) {
        repairType['repairType'] = 0;
      } else {
        repairType['repairType'] = 1;
      }
      state.dialogRefresh = Math.random()
      break
    case 'submit':
      if (state.row) {
        const params = data.data
        params['deviceId'] = state.row.id
        addBmsDeviceRepairApi(params).then((data: any) => {
          if (data.code === 0) {
            ElMessage.success({message: '保存成功！'})
            state.visible = false
          } else {
            console.log('callBackDialog', data)
            ElMessage.warning({message: '保存失败！'})
          }
        })
      }
      break
  }
}

const callBack = (data: any) => {
  switch (data.type || '') {
    case 'dialogClose':
      state.visible = false
      state.historyVisible = false
      break
    case 'submit':
      state.searchData = JSON.parse(JSON.stringify(data.data))
      listDevicePage(state.searchData)
      break
    case 'rest':
      state.searchData = {}
      state.table.pageIndex = 1
      state.table.pageSize = 15
      listDevicePage()
      break
    case 'page':
      state.searchData['pageIndex'] = data.data
      state.searchData['pageSize'] = state.table.pageSize
      listDevicePage(state.searchData)
      break
    case 'pageSize':
      state.searchData['pageIndex'] = state.table.pageIndex
      state.searchData['pageSize'] = data.data
      state.table.pageSize = data.data
      listDevicePage(state.searchData)
      break
    case 'record':
      state.visible = true
      state.row = data.data
      state.deviceForm = JSON.parse(JSON.stringify(deviceForm))
      break
    case 'history':
      state.historyVisible = true
      state.row = data.data
      break
    case 'circulation':
      state.replaceForm = JSON.parse(JSON.stringify(deviceReplaceForm))
      state.replaceVisible = true
      state.row = data.data
      if (state.row && state.organizationList) {
        const card = state.replaceForm[0].card
        const organization = card.find(({name = ''}) => name == 'targetOrganizationId')
        if (!organization) {
          return false
        }
        state.organizationList.forEach(({name = '', id = ''}) => {
          if (state.row.organizationId != id) {
            organization?.options?.push({label: name, value: id})
          }
        })
        // 当前机构
        const sourceOrganization = state.organizationList.find((f: any) => f.id === state.row.organizationId) || {name: ''}
        const cardSource = card.find(({name = ''}) => name === 'sourceOrganizationName')
        // eslint-disable-next-line no-case-declarations
        cardSource['sourceOrganizationName'] = sourceOrganization?.name || ''
        state.replaceRefresh = Math.random()
      }
      break
    case 'see':
      router.push({
        path: '/device/see-device', query: {
          id: data.data.id, dictionary: data.data.dictionaryCode, code: data.data.constCode
        }
      })
      break
    case 'edit':
      router.push({
        path: '/device/edit-device', query: {
          id: data.data.id, dictionary: data.data.dictionaryCode, code: data.data.constCode
        }
      })
      break
  }
}

const addDevice = () => {
  router.push({path: '/device/add-device'})
}

const listOrganization = (params: any) => {
  listOrganizationApi(params).then((data: any) => {
    state.organizationList = data
    const card = state.deviceForm[0].card
    const organization = card.find(({name = ''}) => name == 'organizationId')
    data.forEach(({name = '', id = ''}) => {
      organization.options.push({label: name, value: id})
    })
  })
}

const listDictionary = (params: any) => {
  listConstByDictionaryCodesApi(params).then((data: any) => {
    const card = state.deviceForm[0].card
    const deviceType = card.find(({name = ''}) => name == 'constCode')
    data.forEach(({constCode = '', constName = ''}) => {
      if (constCode && constName) {
        deviceType.options.push({label: constName, value: constCode})
      }
    })
  })
}

const listDevicePage = (params = {pageIndex: 1, pageSize: 15} as any) => {
  if (!params['organizationId']) {
    params['organizationId'] = '-1'
  }
  if (!params['topOrganizationId']) {
    params['topOrganizationId'] = '-1'
  }
  listDevicePageApi(params).then((data: any) => {
    if (data.code === 0) {
      state.data = data.data
      state.table.total = data.total
      state.table.pageSize = data.pageSize
      state.table.pageIndex = data.pageIndex
    }
  })
}

</script>
